<script setup>
import { onMounted, ref } from 'vue';

const text = ref('');
const previewRef = ref();
const content = ref();
const titleList = ref([]);

onMounted(() => {

    fetch('md/js/cmp.md')
        .then(res => res.text())
        .then(md => {
            text.value = md;

            setTimeout(() => {
                createToc();
            }, 200)
        })
})

/**
 * 创建大纲
 */
const createToc = () => {
    const anchors = previewRef.value.$el.querySelectorAll("h1,h2,h3,h4,h5,h6");

    const titles = Array.from(anchors).filter(
        (title) => !!title.innerText.trim()
    );

    if (!titles.length) {
        titleList.value = [];
        return;
    }

    const hTags = Array.from(
        new Set(titles.map((title) => title.tagName))
    ).sort();

    titleList.value = titles.map((el) => ({
        title: el.innerText,
        lineIndex: el.getAttribute("data-v-md-line"),
        indent: hTags.indexOf(el.tagName),
    }));
};

/**
 * 锚点跳转
 */
const handleAnchorClick = (anchor) => {
    const { lineIndex } = anchor;

    const heading = previewRef.value.$el.querySelector(
        `[data-v-md-line="${lineIndex}"]`
    );
    console.log(previewRef.value);

    if (heading) {
        previewRef.value.scrollToTarget({
            target: heading,
            scrollContainer: content.value,
            top: 20,
        });
    }
};


</script>
<template>
    <div class="w-full h-full overflow-y-auto  bg-#fff" ref="content">
        <v-md-preview :text="text" ref="previewRef"></v-md-preview>
    </div>

    <div
        class="fixed right-20px top-20px w-300px pl-10px py-12px bg-#000000aa mr-10px box-border text-14px shadow z-999">
        <div v-for="anchor in titleList" :style="{ padding: `0 0 0 ${anchor.indent * 10}px`  }"
            @click="handleAnchorClick(anchor)">
            <a class="color-#fff cursor-pointer hover:color-#ffffffaa">{{
                anchor.title
                }}</a>
        </div>
    </div>
</template>
<style lang="scss" scoped></style>